import { ElMessageBox, ElMessage } from 'element-plus';
import { HandleData } from './interface';
import { isSpacing } from '@/utils/is';

/**
 * @description 操作单条数据信息 (二次确认【删除、禁用、启用、重置密码】)
 * @param {Function} api 操作数据接口的api方法 (必传)
 * @param {Object} params 携带的操作数据参数 {id,params} (必传)
 * @param {String} message 提示信息 (必传)
 * @param {String} confirmType icon类型 (不必传,默认为 warning)
 * @returns {Promise}
 */
export const useHandleData = (
  api: (params: any) => Promise<any> | any,
  params: any = {},
  message: string,
  db?: undefined | (() => void) | ((params?: undefined | any) => Promise<void>),
  confirmType: HandleData.MessageType = 'warning'
) => {
  return new Promise((resolve, reject) => {
    ElMessageBox.confirm(
      `${transitionLanguages('basic', 'whether')}${isSpacing()}${message}?`,
      transitionLanguages('basic', 'gentleReminder'),
      {
        confirmButtonText: transitionLanguages('button', 'confirm'),
        cancelButtonText: transitionLanguages('button', 'cancel'),
        type: confirmType,
        draggable: true
      }
    )
      .then(async () => {
        await api(params);
        db && db();
        ElMessage({
          type: 'success',
          message: transitionLanguages('basic', 'operateSuccessfully')
        });
        resolve(true);
      })
      .catch(err => {
        reject(err);
      });
  });
};
